<?php

namespace App\Admin\Controllers\Admin;

use App\Notifications\SystemNotification;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Http\Controllers\AuthController as BaseAuthController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseAuthController
{
    protected $view = 'admin.login';

    public function getLogin(Content $content)
    {
        if ($this->guard()->check()) {
            return redirect($this->getRedirectPath());
        }

        return $content->full()->body(view($this->view));
    }

    /**
     * Handle a login request.
     *
     * @param  Request  $request
     * @return mixed
     */
    public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);
        $remember = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => 'required',
            'password'          => 'required',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }
        $key = sprintf("admin:%s:%s",'login-error',$this->username());
        $number = Redis::get($key);

        if($number > 10){
            return $this->validationErrorsResponse([
                $this->username() => "密码错误次数太多，账号暂时冻结",
            ]);
        }

        if ($this->guard()->attempt($credentials, $remember)) {
            return $this->sendLoginResponse($request);
        }

        if(!Redis::exists('key')){
            Redis::setnx($key,0);
            Redis::expire($key,strtotime("tomorrow") - time());
        }
        Redis::incrby($key,1);
        if (Redis::get($key) == 5){
            $admin = \App\Models\Admin\Admin::where("username",$credentials[$this->username()])->first();
            $admin->notify(new SystemNotification("用户登录密码错误次数过多",'可能有人在尝试登录你的账号，请注意账号安全',2));
        }
        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }

    protected function settingForm()
    {
        return Form::make(new EloquentRepository(Administrator::class),function (Form $form){

            $form->action(admin_url('auth/setting'));

            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();

            $form->tools(function (Form\Tools $tools) {
                $tools->disableView();
                $tools->disableDelete();
            });

            $form->block(7,function (Form\BlockForm $form){
                // 设置标题
                $form->title('基本设置');
                // 显示底部提交按钮
                $form->showFooter();
                // 设置字段宽度
                $form->width(9, 2);


                $form->column(6, function (Form\BlockForm $form) {
                    $form->display('username', trans('admin.username'));
                    $form->password('old_password', trans('admin.old_password'));

                    $form->password('password', trans('admin.password'))->minLength(5)
                        ->maxLength(20)
                        ->customFormat(function ($v) {
                            return "";
                        });
                    $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');
                    $form->ignore(['password_confirmation', 'old_password']);
                });

                $form->column(6, function (Form\BlockForm $form) {
                    $form->text('name', trans('admin.name'))->required();
                    $form->image('avatar', trans('admin.avatar'))->autoUpload();
                });
            });

            /*$form->block(5,function (Form\BlockForm $form){
                // 设置标题
                $form->title('操作设置');
                // 显示底部提交按钮
                #$form->showFooter();
                // 设置字段宽度
                $form->width(9, 2);


                $form->text('theme', "主题");
            });*/

            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }

                if (! $form->password) {
                    $form->deleteInput('password');
                }
            });

            $form->saved(function (Form $form) {
                return $form->response()->success(trans('admin.update_succeeded'))->redirect('auth/setting');
            });
        });
    }


    public function putSetting()
    {
        $form = $this->settingForm();

        if (! $this->validateCredentialsWhenUpdatingPassword()) {
            $form->responseValidationMessages('old_password', trans('admin.old_password_error'));
        }

        $form->update(Admin::user()->getKey());

        $request = request();
        if($request->post("password")){
            $this->guard()->logout();
            $request->session()->invalidate();
        }

        return $this->response()->success('设置成功')->refresh();
    }
}
